package se.boars.dailystatistics;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class main extends Activity {
    /** Called when the activity is first created. */
	
	TelephonyManager phoneManager;
	JSONParser jParser;
	JSONObject checkAnswer;
	TextView errorText;
	TextView questionTitle;
	ListView qList;
	Intent service;
	View view;
	Button voteButton;
	ProgressDialog progressDialog;
	String errorTextData;
	String imeiNumber;
	CharSequence[] questionData;
	ArrayAdapter<CharSequence> listAdapter;
	SharedPreferences settings;
	int questionID;
	int responseCode;
	long qAnswer;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        settings = PreferenceManager.getDefaultSharedPreferences(this);
        
        phoneManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        imeiNumber = phoneManager.getDeviceId();
        jParser = new JSONParser();
        qList =(ListView)findViewById(R.id.listView1);
        errorText=(TextView)findViewById(R.id.textView1);
        questionTitle = (TextView)findViewById(R.id.textView2);
        voteButton =(Button)findViewById(R.id.button1);
        progressDialog = new ProgressDialog(main.this);
        service = new Intent(main.this, bgUpdate.class);
        
        qList.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
            	qAnswer = id;
            	System.out.println(qAnswer);
        	}
        });
    }
    
    protected void onStart() {
    	super.onStart();
    	new printQuestionTask().execute();

    	if(settings.getBoolean("bgupdate", false) == true) {
    		main.this.startService(service);
    	} else {
    		main.this.stopService(service);
    	}
    }
    
    protected void onResume() {
    	super.onResume();
    	new printQuestionTask().execute();  
    	
    	if(settings.getBoolean("bgupdate", false) == true) {
    		main.this.startService(service);
    	} else {
    		main.this.stopService(service);
    	}

    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.menuRefresh:
    		new printQuestionTask().execute();
    		return true;
    	case R.id.menuSettings:
    		startActivity(new Intent(this, Preferences.class));
    	}
    	return false;
    }
    
    public void clickHandler(View view) throws JSONException {
    	switch(view.getId()) {
    	case R.id.button1:
    		new submitVoteTask().execute();
    	}
    }
    
    public String printError(View view, int id) {
    	if (id == 0) {
    		String error = "No question available yet";
    		return error;
    	}
    	else if(id == 2) {
    		String error = "You have already answered todays question, check back tomorrow";
    		return error;
    	}
    	else {
    		String error = "";
    	}
    	return null;
    }
    
    private class printQuestionTask extends AsyncTask<Void, Void, Void> {
    	@Override
    	protected void onPreExecute() {
    		progressDialog.setMessage("Retrieving Question...");
    		progressDialog.show();
    	}
    	
		@Override
		protected Void doInBackground(Void... arg0) {
			try {
				getQuestion();
			} catch(Exception e) {
				System.out.println("Error in thread in doInBackground");
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			System.out.println("Executed printQuestionTask successfully");
			progressDialog.dismiss();
			try {
				printQuestionToList(view);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    	
    }
    
    public void getQuestion() {
    	try {
    		
    		ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    		param.add(new BasicNameValuePair("tag", "getQuestion"));
    		JSONObject qObj = jParser.getJSONObjectFromWeb("http://108.174.49.135/rewrite/api.php",param);
    		
    		if(qObj.getInt("response") == 0) {
    			responseCode = qObj.getInt("response");
    		} else {
    			responseCode = qObj.getInt("response");
    			questionID = qObj.getInt("questionID");
    			questionData = new CharSequence[] {qObj.getString("question"), qObj.getString("answerA"), qObj.getString("answerB"), qObj.getString("answerC") };
    		}
    		checkAnswer = checkIfAnswered();
    	}catch(Exception e) {
    		System.out.println("Error in getQuestion: " + e);
    	}
    }
    
    public void printQuestionToList(View view) throws JSONException {
    	System.out.println("Printing the question to list");
    	errorText.setText(printError(view, responseCode));
	
    	if(responseCode == 1){
    	questionTitle.setText(questionData[0]);
    	CharSequence[] answers = new CharSequence[] {questionData[1], questionData[2], questionData[3] };
    	
    	listAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_single_choice, answers);
    	qList.setItemsCanFocus(false);
    	qList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    	qList.setAdapter(listAdapter);
    	}
    	else if(responseCode == 0) {
    		voteButton.setEnabled(false);
    		questionTitle.setText("");
    		qList.setAdapter(null); 	
    	}
    	
    	if(checkAnswer.getBoolean("answered") == false) {
			if(voteButton.isEnabled() == false) {
				voteButton.setEnabled(true);
			}
			if(qList.isEnabled() == false) {
				qList.setEnabled(true);
				qList.setVisibility(View.VISIBLE);
			}
    	}
    	else {
    		errorText.setText(printError(view, 2));
			qList.setItemChecked(checkAnswer.getInt("answer"),true);
			qList.setEnabled(false);
			qList.setEnabled(false);
			voteButton.setEnabled(false);
    	}
    }
    
    private class submitVoteTask extends AsyncTask<Void, Void, Void> {
    	
    	@Override
    	protected void onPreExecute() {
    		progressDialog.setMessage("Submitting vote...");
    		progressDialog.show();
    	}
    	
		@Override
		protected Void doInBackground(Void... params) {
			submitVote();
			try {
				checkAnswer = checkIfAnswered();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			progressDialog.dismiss();
			AlertDialog.Builder builder = new AlertDialog.Builder(main.this);
			builder.setMessage("Answer submitted successfully")
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
				}
		});
			AlertDialog alert = builder.create();
			alert.show();
			try {
				printQuestionToList(view);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//new printQuestionTask().execute();
		}
    }
    
    public void submitVote() {
    	ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    	param.add(new BasicNameValuePair("tag", "submitVote"));
    	param.add(new BasicNameValuePair("answer", "" + qAnswer));
    	param.add(new BasicNameValuePair("questionid", "" + questionID));
    	param.add(new BasicNameValuePair("userid", imeiNumber));
    	
    	jParser.getJSONObjectFromWeb("http://108.174.49.135/rewrite/api.php", param);
    }
    
    public JSONObject checkIfAnswered() throws JSONException {
    	ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    	param.add(new BasicNameValuePair("tag", "checkIfAnswered"));
    	param.add(new BasicNameValuePair("userid", imeiNumber));
    	
    	JSONObject haveAnsweredCheck= jParser.getJSONObjectFromWeb("http://108.174.49.135/rewrite/api.php", param);
    	return haveAnsweredCheck;
    }   
}
